/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("big_data_basic",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using VOL.JIRUI.IServices;
using VOL.Core.Configuration;
using SapNwRfc;
using Microsoft.AspNetCore.Authorization;
using VOL.Core.Filters;
using VOL.Core.DBManager;
using VOL.Core.Extensions;
using System.Linq;
using System.Globalization;
using Microsoft.VisualBasic;

namespace VOL.JIRUI.Controllers
{
    public partial class big_data_basicController
    {
        private readonly Ibig_data_basicService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public big_data_basicController(
            Ibig_data_basicService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 大数据平台获取SAP中创建的VIN码相关数据
        /// </summary>
        /// <returns></returns>
        ///[ApiTask]
        [HttpGet,HttpPost, Route("get_sap_vin"), AllowAnonymous] 
        public dynamic get_sap_vin()
        {
            // 从参数表中获取对应的参数值
            big_data_execute_parameter big_data_execute_parameter = DBServerProvider.DbContext.Set<big_data_execute_parameter>().Where(x => x.type == "get_sap_vin").FirstOrDefault();
            string START_DATE = big_data_execute_parameter.parameter;
            string END_DATE = big_data_execute_parameter.parameter1;
            string newDate = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            if (big_data_execute_parameter.manual_setting == 0 && !START_DATE.Equal(newDate))
            {
                START_DATE = newDate;
                END_DATE = newDate;
            }
            string connectionString = AppSetting.GetSection("SAP_ECC_CONN")["connstr"];
            using var connection = new SapConnection(connectionString);
            connection.Connect();
            using var someFunction = connection.CreateFunction("Z_GET_VIN_DATA");
            List<SomeFunctionitem> ils2 = new List<SomeFunctionitem>();
            var result = someFunction.Invoke<SomeFunctionResult>(new SomeFunctionParameters
            {
                START_DATE = START_DATE,
                END_DATE = END_DATE,
            });
            for (int ii = 0; ii < result.ZRETURN.Length; ii++)
            {
                ils2.Add(result.ZRETURN[ii]);
            }
            foreach (var item in ils2)
            {
                big_data_basic big_data_basicQuery = DBServerProvider.DbContext.Set<big_data_basic>().Where(t => t.equipment_number == item.EQUNR).FirstOrDefault();
                if (big_data_basicQuery.IsNullOrEmpty())
                {
                    big_data_basic big_data_basic = new big_data_basic();
                    big_data_basic.big_data_basic_id = Guid.NewGuid();
                    big_data_basic.equipment_number = item.EQUNR;
                    big_data_basic.vin = item.SERNR;
                    big_data_basic.matecode = item.MATNR;
                    big_data_basic.matedesc = item.MAKTX;
                    big_data_basic.model_name = item.SPART;
                    big_data_basic.evaluation = item.BKLAS;
                    big_data_basic.evaluation_name = item.BKBEZ;
                    big_data_basic.werks = item.WERKS;
                    // sap传递数据的时候，如果有字段为空，会补0
                    big_data_basic.ERDAT = item.ERDAT == "00000000" ? null : DateTime.ParseExact(item.ERDAT, "yyyyMMdd", CultureInfo.CurrentCulture);
                    big_data_basic.AUFNR = item.AUFNR;
                    // sap传递数据的时候，如果有字段为空，会补0
                    big_data_basic.cheduling_time = item.CJRQ == "00000000" ? null : DateTime.ParseExact(item.CJRQ, "yyyyMMdd", CultureInfo.CurrentCulture);
                    big_data_basic.dms_order_no = item.BSTKD;
                    big_data_basic.Creator = "SAP";
                    big_data_basic.CreateDate = DateTime.Now;
                    big_data_basic.status = 0;
                    DBServerProvider.DbContext.Add(big_data_basic);
                }
                else
                {
                    big_data_basicQuery.equipment_number = item.EQUNR;
                    big_data_basicQuery.vin = item.SERNR;
                    big_data_basicQuery.matecode = item.MATNR;
                    big_data_basicQuery.matedesc = item.MAKTX;
                    big_data_basicQuery.model_name = item.SPART;
                    big_data_basicQuery.evaluation = item.BKLAS;
                    big_data_basicQuery.evaluation_name = item.BKBEZ;
                    big_data_basicQuery.werks = item.WERKS;
                    big_data_basicQuery.AEDAT = item.AEDAT == "00000000" ? null : DateTime.ParseExact(item.AEDAT, "yyyyMMdd", CultureInfo.CurrentCulture);
                    big_data_basicQuery.AUFNR = item.AUFNR;
                    big_data_basicQuery.cheduling_time = item.CJRQ == "00000000" ? null : DateTime.ParseExact(item.CJRQ, "yyyyMMdd", CultureInfo.CurrentCulture);
                    big_data_basicQuery.dms_order_no = item.BSTKD;
                    big_data_basicQuery.Modifier = "SAP";
                    big_data_basicQuery.ModifyDate = DateTime.Now;
                    big_data_basicQuery.status = 0;
                    DBServerProvider.DbContext.Update(big_data_basicQuery);
                }
            }
            if (big_data_execute_parameter.manual_setting == 1 || !big_data_execute_parameter.parameter.Equal(newDate))
            {
                big_data_execute_parameter.parameter = newDate;
                big_data_execute_parameter.parameter1 = newDate;
                big_data_execute_parameter.manual_setting = 0;
                big_data_execute_parameter.Modifier = "系统";
                big_data_execute_parameter.ModifyDate = DateTime.Now;
                DBServerProvider.DbContext.Update(big_data_execute_parameter);
            }
            DBServerProvider.DbContext.SaveChanges();
            return ils2.Count;
        }

        /// <summary>
        /// 输入参数
        /// </summary>
        class SomeFunctionParameters
        {
            [SapName("START_DATE")]
            public string START_DATE { get; set; }
            [SapName("END_DATE")]
            public string END_DATE { get; set; }
        }

        /// <summary>
        /// 输出参数名称
        /// </summary>
        class SomeFunctionResult
        {
            [SapName("ZRETURN")]
            public SomeFunctionitem[] ZRETURN { get; set; }
        }
        /// <summary>
        /// 对应的SAP中返回的结构
        /// </summary>
        public class SomeFunctionitem
        {
            public string EQUNR { get; set; }//设备编号
            public string SERNR { get; set; }//SAP序列号（vin）
            public string MATNR { get; set; }//整车物料号
            public string MAKTX { get; set; }//物料描述（短文本）
            public string SPART { get; set; }//SAP物料主数据-产品组
            public string BKLAS { get; set; }//评估类
            public string BKBEZ { get; set; }//评估类描述
            public string WERKS { get; set; }//工厂/生产基地
            public string ERDAT { get; set; }//下达日期
            public string AEDAT { get; set; }//修改日期
            public string AUFNR { get; set; }//生产订单号
            public string CJRQ { get; set; }//排产时间
            public string BSTKD { get; set; }//DMS订单号

        }
    }
}
